package com.ikkong.qy.controller;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.common.collect.Maps;
import com.ikkong.biz.model.WeixinUser;
import com.ikkong.biz.model.WxFile;
import com.ikkong.common.config.MainConfig;
import com.ikkong.core.base.BaseController;
import com.ikkong.core.constant.ConstCache;
import com.ikkong.core.constant.Cst;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.dao.Db;
import com.ikkong.core.jfinal.ext.kit.JStrKit;
import com.ikkong.core.jfinal.ext.kit.JsonKit;
import com.ikkong.core.toolbox.kit.CharsetKit;
import com.ikkong.core.toolbox.kit.CollectionKit;
import com.ikkong.core.toolbox.kit.URLKit;
import com.ikkong.qy.core.WeixinBaseController;
import com.ikkong.qy.util.CommonUtils;
import com.ikkong.qy.util.WeixinApi;
import com.ikkong.qy.util.WeixinInterface;
import com.ikkong.system.model.Attach;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.ehcache.CacheKit;
import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.swetake.util.Qrcode;

public class WeixinInterController extends WeixinBaseController {

	public void checkNotice(){
		String userId = getPara("userId");
		Map<String, Object> resultMap = null;
		
		try {
			List<Map> noticeList = Db.init().queryListMap("select cast(nr.notice_id as char) as noticeId,n.title,n.content,n.cname as sender,date_format(n.ctime,'%Y-%m-%d %H:%i') as time"
					+ " from tb_notice_result nr,tb_notice n where nr.customer_id = "+userId+" and nr.customer_type = 1 and nr.is_read = 0 and nr.notice_id = n.id order by n.ctime desc;");
			resultMap = new HashMap<String, Object>();
			resultMap.put("success", "true");
			resultMap.put("msg", "成功");
			resultMap.put("data", noticeList);
			renderJson(resultMap);
			return;
		} catch (Exception e) {
			e.printStackTrace();
		}
		resultMap = new HashMap<String, Object>();
		resultMap.put("success", "false");
		resultMap.put("msg", "服务器错误");
		renderJson(resultMap);
	}
	
	public void route(){
		System.out.println(Cst.me().getRealPath());
		System.out.println(Cst.me().getContextPath());
		getUser();
		String state = getPara("state");
		String[] array = state.split("_");
		String action = array[0];
		if("noticelist".equals(action)){			
			String type = "1";
			if(array.length > 1){
				type = array[1];
			}
			redirect(Cst.me().getBasePath()+"/weixinNotice/list?type="+type);
			
		}else if("noticeview".equals(action)){			
			String noticeId = "";
			if(array.length > 1){
				noticeId = array[1];
			}
			redirect(Cst.me().getBasePath()+"/weixinNotice/view/"+noticeId);
			
		}else if("noticesend".equals(action)){						
			redirect(Cst.me().getBasePath()+"/weixinNotice/send");
			
		}else if("detail".equals(action)){				
			String id = "1";
			if(array.length > 1){
				id = array[1];
			}
			String type = "1";
			if(array.length > 1){
				type = array[2];
			}
			redirect(Cst.me().getBasePath()+"/weixinContact/detail?id="+id+"&type="+type);
			
		}else if("contact".equals(action)){				
			String id = "1";
			if(array.length > 1){
				id = array[1];
			}
			String type = "1";
			if(array.length > 1){
				type = array[2];
			}
			redirect(Cst.me().getBasePath()+"/weixinContact/listDept");
		} else if("login".equals(action)){
            String weixinUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={}&redirect_uri={}&response_type=code&scope=snsapi_userinfo&state=qr_{}#wechat_redirect";
            String redirctUrl = PropKit.get("config.basePath")+"/weixinInter/doLogin";
            String id = "1";
            if(array.length > 1){
                id = array[1];
            }
            weixinUrl = JStrKit.format(weixinUrl, MainConfig.map.get("weixin.corpId"),URLKit.encode(redirctUrl,CharsetKit.UTF_8),id);
            redirect(weixinUrl);

        } else if("flowsend".equals(action)){
			redirect(Cst.me().getBasePath()+"/weixinFlow/start");
        } else if("flowReceived".equals(action)){
			redirect(Cst.me().getBasePath()+"/weixinFlow/listReceived");
        } else if("flowSended".equals(action)){
			redirect(Cst.me().getBasePath()+"/weixinFlow/listSended");
        } else if("flowview".equals(action)){
        	String flowId = "";
			if(array.length > 1){
				flowId = array[1];
			}
			redirect(Cst.me().getBasePath()+"/weixinFlow/view/"+flowId);
        }
		
		
	}
	
	public void recNotice(){
		String userId = getPara("userId");
		String noticeId = getPara("noticeId");
		Map<String, Object> resultMap = null;
		
		try {
			Db.init().update("update tb_notice_result set is_read = 1 where customer_id = "+userId
					+" and notice_id = "+noticeId+" and customer_type = 1", null);
			resultMap = new HashMap<String, Object>();
			resultMap.put("success", "true");
			resultMap.put("msg", "成功");
			renderJson(resultMap);
			return;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		resultMap = new HashMap<String, Object>();
		resultMap.put("success", "false");
		resultMap.put("msg", "服务器错误");
		renderJson(resultMap);
	}	
	
	public void reset(){
		try {
			Db.init().update("update tb_notice_result set is_read = 0",null);
			HashMap resultMap = new HashMap<String, Object>();
			resultMap.put("success", "false");
			resultMap.put("msg", "服务器错误");
			renderJson(resultMap);
			return;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		HashMap resultMap = new HashMap<String, Object>();
		resultMap.put("success", "false");
		resultMap.put("msg", "服务器错误");
		renderJson(resultMap);
	}

	public void getImage(){
		String sms_info = getPara("param");

        String redirectUrl = "http://justskier.tunnel.qydev.com/weixinInter/auth?param={}";
        sms_info = JStrKit.format(redirectUrl,sms_info);
        System.out.println(sms_info);
		try {
			Qrcode testQrcode = new Qrcode();
			testQrcode.setQrcodeErrorCorrect('M');
			testQrcode.setQrcodeEncodeMode('B');
			testQrcode.setQrcodeVersion(7);
			String testString = sms_info;
			byte[] d = testString.getBytes("gbk");
			BufferedImage bi = new BufferedImage(180, 180,
					BufferedImage.TYPE_BYTE_BINARY);
			Graphics2D g = bi.createGraphics();
			g.setBackground(Color.WHITE);
			g.clearRect(0, 0, 360, 360);
			g.setColor(Color.BLACK);

			boolean[][] s = testQrcode.calQrcode(d);
			for (int i = 0; i < s.length; i++) {
				for (int j = 0; j < s.length; j++) {
					if (s[j][i]) {
						g.fillRect(j * 4, i * 4, 4,4);
					}
				}
			}
			g.dispose();
			bi.flush();
			ImageIO.write(bi, "jpg", getResponse().getOutputStream());
			renderNull();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void checkQRLogin(){
        String param = this.getPara("param");
        Object obj = CacheKit.get(ConstCache.WEIXIN_CACHE,param);
        Map<String,Object> resultMap = Maps.newHashMap();
        if(obj == null){
            resultMap.put("success", "false");
            resultMap.put("msg", "用户未授权");
            renderJson(resultMap);
        }else{
            WeixinUser user = (WeixinUser)obj;
            resultMap.put("success", "true");
            resultMap.put("msg", "登录成功");
            resultMap.put("userId", user.getId());
            renderJson(resultMap);
        }
    }

    public void qrcode(){
        render("/weixin/login/qrcode.html");
    }

    public void auth(){
        setAttr("param", this.getPara("param"));
        render("/weixin/login/auth.html");
    }

    public void doLogin(){
        String code = this.getPara("code");
        if (JStrKit.isBlank(code)){
            render("/weixin/login/error.html");
            return;
        }
        String state = this.getPara("state");
        String param = state.replace("qr_","");
        WeixinUser user = this.getUser();
        if (null==user){
            render("/weixin/login/error.html");
            return;
        }
        CacheKit.put(ConstCache.WEIXIN_CACHE,param,user);
        render("/weixin/login/success.html");
    }
    
    public void pushFile(){
    	Map param = getParaMap();
    	CommonUtils.tPrint(param, "pushFile");
    	
    	String msg_signature = getPara("msg_signature");
    	String timestamp = getPara("timestamp");
    	String nonce = getPara("nonce");
    	String echostr = getPara("echostr");
    	
		WXBizMsgCrypt bizMsgCrypt = WeixinApi.getWxBizMsgCrypt();
    	
    	if(!JStrKit.isBlank(echostr)){
        	try {
    			String echor = bizMsgCrypt.VerifyURL(msg_signature, timestamp, nonce, echostr);
    			
    			System.out.println(echor);
    			
    			getResponse().getWriter().write(echor);
    			getResponse().getWriter().close();
    			renderNull();
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	StringBuilder sb = new StringBuilder();
    	try {
			BufferedReader reader = new BufferedReader(getRequest().getReader());
			String temp = reader.readLine();
			while(temp != null){
				sb.append(temp);
				temp = reader.readLine();
			}
			System.out.println(sb.toString());
			String result = bizMsgCrypt.DecryptMsg(msg_signature, timestamp, nonce, sb.toString());
			System.out.println(result);
			Map<String, String> map = WeixinApi.parseXml(result);
			
			String msgType = map.get("MsgType");
			CommonUtils.tPrint(map, "xml");
			if("image".equals(msgType)){
				String mediaId =map.get("MediaId");
				System.out.println(mediaId);
				Attach attach = WeixinInterface.downloadPic(mediaId);
				WxFile file = new WxFile();
				file.setAttach_id(attach.getId());
				file.setUser_mobile(map.get("FromUserName"));
				file.setStatus(0);
				file.setCtime(new Date());
				file.setType(1);
				file.setName(attach.getName());
				file.setThumb_url(attach.getUrl());
				Blade.create(WxFile.class).save(file);
				
				
			}else if("video".equals(msgType)||"shortvideo".equals(msgType)){
				String mediaId =map.get("MediaId");
				Attach attach = WeixinInterface.downloadVideo(mediaId);
				
				mediaId =map.get("ThumbMediaId");
				Attach thumbAttach = WeixinInterface.downloadPic(mediaId);

				WxFile file = new WxFile();
				file.setAttach_id(attach.getId());
				file.setUser_mobile(map.get("FromUserName"));
				file.setStatus(0);
				file.setCtime(new Date());
				file.setType(2);
				file.setThumb_url(thumbAttach.getUrl());
				file.setName(attach.getName());
				Blade.create(WxFile.class).save(file);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	
    }
	
}
